<template>
    <div class="page-wrapper juge-page">
        <scroll :data="needDownloadFiles">
            <el-form class="juge-form"  label-width="0" label-position="left">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label-width="68px" label="用户Id" style="width: 100%;margin-bottom: 0" >
                            <el-row>
                                <el-col :span="23">
                                    <el-input :disabled="Auto" :clearable="true" style="margin-left: 0" size="mini" v-model="form.Id"></el-input>
                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8" style="text-align: center">
                        <el-date-picker
                                data-microtip="只限最近7天" data-microtip-position="bottom"
                                style="width: 140px;margin-top: 7px"
                                size="mini"
                                v-model="form.date"
                                type="date"
                                placeholder="选择日期"
                                value-format="MM/dd/yyyy"
                        >
                        </el-date-picker>
                    </el-col>

                    <el-col :span="10">
                        <el-form-item style="width: 100%;margin-bottom: 0" >
                            <el-row>
                                <el-col :span="8">
                                    <el-input  :disabled="true" style="margin-left: 0" size="mini" v-model="form.path"></el-input>
                                </el-col>

                                <el-col :span="15" :push="1">

                                    <el-button-group class="juge-operationGroup">
                                        <el-button  data-microtip="更改路径" data-microtip-position="bottom"  @click="handleSelectSavePath" size="mini" type="primary" icon="iconfont icon-xuanzeshebei"></el-button>
                                        <el-button  data-microtip="打开文件夹" data-microtip-position="bottom"  @click="openDirPath" :disabled="form.path === ''" icon="iconfont icon-wenjian1" size="mini" type="primary"></el-button>
                                        <el-button  data-microtip="扫描文件" data-microtip-position="bottom"  :disabled="form.Id ==='' || form.path === ''" icon="iconfont icon-scan" @click="handleScanDir"  size="mini" type="primary"></el-button>
                                        <el-button  data-microtip="自动扫描" data-microtip-position="bottom"   :disabled="form.Id ===''" @click="switchAuto" v-if="!Auto" size="mini" type="primary" icon="iconfont icon-zidongfaxian"></el-button>
                                        <el-button  data-microtip="扫描中..." data-microtip-position="bottom"  @click="switchAuto" v-else size="mini" type="danger" icon="iconfont icon-zidongfaxian"></el-button>
                                    </el-button-group>

                                </el-col>
                            </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div class="juge-table">

                    <div class="uge-table-title" style="padding: 5px 0 10px 0 ">

                        <el-button-group class="juge-operationGroup">
                            <el-button type="primary" @click="batchDownload"  icon="el-icon-share" size="mini"  data-microtip="批量下载" data-microtip-position="top">
                                批量下载
                            </el-button>
                            <el-button type="primary" @click="emptyTableData"  icon="el-icon-delete" size="mini"  data-microtip="清空" data-microtip-position="top">
                                清空列表
                            </el-button>
                        </el-button-group>


                    </div>

                    <div class="juge-table-main">

                        <el-table
                                :data="needDownloadFiles"
                                style="width: 100%;margin-bottom: 10px"
                                size="mini"
                                height="230"
                                @selection-change="selected => selectedItems = selected"
                                border
                        >

                            <el-table-column
                                    type="selection"
                                    width="40">
                            </el-table-column>

                            <el-table-column
                                    type="index"
                                    width="30">
                            </el-table-column>


                            <el-table-column
                                    prop="Id"
                                    label="Id"
                                    width="60px"
                            >
                            </el-table-column>
                            <el-table-column
                                    width="160px"
                                    prop="TbOrderid"
                                    label="淘宝Id">
                            </el-table-column>
                            <el-table-column
                                    prop="fileId"
                                    label="文件ID">
                            </el-table-column>
                            <el-table-column
                                    prop="time"
                                    label="时间">
                            </el-table-column>

                            <el-table-column label="操作" width="60px">
                                <template slot-scope="scope">
                                    <el-button  @click="downloadFile(scope.row)" type="text" size="mini">下载</el-button>
                                </template>
                            </el-table-column>

                        </el-table>

                    </div>

                </div>
            </el-form>
        </scroll>
    </div>
</template>

<script>
    import scroll from "@/components/base/pcScroll.vue";
    import walk from "walk"
    import _ from "lodash"
    import Api from "@/api/index.js"
    import {mapGetters} from "vuex"

    export default {
        name: "juge-page",
        components: {
            scroll
        },
        data: function () {
            return {
                Timer:"",
                Auto:false,
                locked: false,
                form: {
                    path: "D:\\Downloads\\test",
                    Id:"229",
                    date:""
                },
                fileId: 0,
                files: [],
                errFiles: [],
                downloadFiles: [],
                jugeTbidFiles: [],
                onlineData: [],
                //需要重新下载的文件
                needDownloadFiles: [],
                selectedItems:[]
            }
        },
        methods: {
            handleSelectSavePath() {
                this.dialog.showOpenDialog({
                    //默认路径
                    defaultPath: '../Desktop',
                    //选择操作，此处是打开文件夹
                    properties: [
                        'openDirectory',
                    ],
                    //过滤条件
                    filters: [
                        {name: 'All', extensions: ['*']},
                    ]
                }, (res) => {
                    //回调函数内容，此处是将路径内容显示在input框内
                    if (res) {
                        this.form.path = res[0];
                    }
                })
            },

            async handleScanDir() {
                try {
                    if (this.locked) return;
                    this.locked = true;
                    this.files = await this.getFileList(this.form.path);
                    let onlineData = await this.getOnlineData();
                    this.resetData();
                    _.delay(() => {
                        if(onlineData){
                            this.getErrFile();
                            this.compareTbid();
                            this.$message.success(`用户ID:${this.form.Id} 扫描成功!`);
                        }else{
                            this.$message.error(`未获得数据`);
                        }
                        this.locked = false;
                    }, 30);
                } catch (e) {
                    this.$message.error("服务器连接失败");
                    console.log(e)
                }
            },
            //获得文件列表
            getFileList(path) {
                return new Promise(resolve => {
                    let files = [], dirs = [];
                    let walker = walk.walk(path, {followLinks: false});
                    walker.on('file', function (roots, stat, next) {
                        files.push(stat.name);
                        next();
                    });

                    walker.on('directory', function (roots, stat, next) {
                        dirs.push(roots + '/' + stat.name);
                        next();
                    });

                    walker.on('end', () => {
                        resolve(files);
                    });
                });
            },
            //获得无效文件后缀的文件
            getErrFile() {
                this.errFiles = [];
                this.downloadFiles = [];
                _.each(this.files, (file, index) => {
                    let FileNameArr = file.split(".");
                    FileNameArr[1] === 'crdownload' ? this.downloadFiles.push(file) : null;
                    FileNameArr.length === 1 ? this.errFiles.push(file) : null;
                    if (FileNameArr.length !== 1 && FileNameArr[1] !== 'crdownload') {
                        let tbId = FileNameArr[0].split("_")[0];
                        tbId ? this.jugeTbidFiles.push(tbId) : null;
                    }
                });
            },
            //获得线上数据
            async getOnlineData() {
                try {
                    let Rs = await  Api.getFileData({
                        date:this.form.date
                    });
                    let newData = {};
                    //分离出自己的数据
                    _.each(Object.keys(Rs), (item) => {
                        let StrArr = item.split("_");
                        if (StrArr.length > 1 && StrArr[1] === this.form.Id) {
                            newData[StrArr[0]] = JSON.parse(Rs[item])
                        }
                    });
                    this.onlineData = newData;
                    return newData;
                } catch (e) {
                    console.log(e)
                }
            },
            //对比tbid 获得本地文件 问题数据
            compareTbid() {
                let cloneJugeTbid = _.cloneDeep(this.jugeTbidFiles);
                let cloneOnlineData = _.cloneDeep(this.onlineData);
                let cloneDownloadFiles = _.cloneDeep(this.downloadFiles);
                let cloneErrFiles = _.cloneDeep(this.errFiles);
                //删除正常的订单
                _.each(cloneJugeTbid, (item) => {
                    delete cloneOnlineData[item];
                });
                //从下载错误的单据中添加信息
                _.each(cloneDownloadFiles, (item) => {
                    let tbId = item.split("_")[0];
                    let needDownloadFile = cloneOnlineData[tbId];
                    if (needDownloadFile) {
                        needDownloadFile.errorType = "下载未完成";
                        this.needDownloadFiles.push(needDownloadFile);
                        delete cloneOnlineData[tbId]
                    }
                });
                //遍历错误文件
                _.each(cloneErrFiles, (fileId) => {
                    _.each(cloneOnlineData, (orderInfo) => {
                        if (fileId === orderInfo.fileId.toString()) {
                            orderInfo.errorType = "下载错误";
                            this.needDownloadFiles.push(orderInfo);
                            delete cloneOnlineData[orderInfo.TbOrderid]
                        }
                    });
                });
                _.each(cloneOnlineData, (order) => {
                    order.errorType = "本地未找到";
                    this.needDownloadFiles.push(order)
                });
            },
            //下载文件
            downloadFile(row,model = 1) {
                let Index = _.indexOf(this.needDownloadFiles,row);
                let href = `${this.downLoadPath || "http://192.168.0.15:8989"}/service/file/download/data/${row.Id}/${row.fileId}`;
                this.$electron.shell.openExternal(href);
                this.needDownloadFiles.splice(Index,1);
                if(model === 1) this.$notify({title: '提示', message: '下载的文件保存在浏览器默认的下载地址', duration: 5000});
                // this.$electron.ipcRenderer.send("download",{
                //     url:href,
                //     directory:this.form.path,
                //     id:this.fileId++
                // });
            },
            
            resetData() {
                this.errFiles = [];
                this.downloadFiles = [];
                this.jugeTbidFiles = [];
                this.needDownloadFiles = [];
            },

            batchDownload(){
                if(this.selectedItems.length === 0){return this.$message.error("没选中任何一个值")}
                this.$confirm('是否批量下载文件', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$notify({
                        title: '提示',
                        message: '下载的文件保存在浏览器默认的下载地址',
                        duration: 5000
                    });
                    _.each(this.selectedItems,(item)=>{
                        setTimeout(()=>{this.downloadFile(item,2)},500);
                    });
                });
            },
            //切换自动模式
            switchAuto(){
                this.Auto = !this.Auto;
                this.Auto
                    ?(()=>{
                        this.handleScanDir();
                        this.Timer = setInterval(()=>{
                            this.handleScanDir()
                        },30 * 1000)
                    })()
                    : clearInterval(this.Timer);
                this.$message.info(this.Auto?"自动扫描开启":"自动扫描关闭")
            },
            //打开文件夹
            openDirPath(){
                let Juge = this.$electron.shell.openItem(this.form.path);
                this.$message({
                    message:Juge?'打开成功!':"打开失败!",
                    type: Juge?'success':"error"
                });
            },
            //清空table
            emptyTableData(){
                this.needDownloadFiles = [];
            }
        },
        computed: {
            dialog() {
                return this.$electron.remote.dialog
            },
            ...mapGetters(['downLoadPath'])
        },
        async mounted() {
            try {
                await this.getOnlineData();
            } catch (e) {
                console.log(e)
            }
        }
    }
</script>

<style lang="less">
    .juge-page {
        padding: 5px 30px 0px 30px;
        .page-title {
            padding: 10px 0 30px;
        }
        .juge-form {
            width: 100%;
            &-row {
                display: flex;
                width: 100%;
                margin-top: 30px;
                align-items: center;
            }
            .el-form-item__label, .el-checkbox__label {
                color: #fff;
            }

            &-twoRow {
                .el-form-item__label {
                    float: none;
                    display: inline-block;
                    text-align: left;
                }
                .el-form-item__content {
                    margin-left: 0 !important;
                }
            }
        }

        .juge-operationGroup{
            .el-button--mini{
                padding: 7px 8px;
            }
        }
    }
</style>
